package com.iheima.reggie_take.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iheima.reggie_take.common.CustomException;
import com.iheima.reggie_take.dto.SetmealDto;
import com.iheima.reggie_take.entity.Setmeal;
import com.iheima.reggie_take.entity.SetmealDish;
import com.iheima.reggie_take.service.SetmealDishService;
import com.iheima.reggie_take.service.SetmealService;
import com.iheima.reggie_take.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author fzykd
* @description 针对表【setmeal(套餐)】的数据库操作Service实现
* @createDate 2023-01-18 14:53:04
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
    implements SetmealService{


    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐 保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息 操作setmeal 套餐表 执行insert
        this.save(setmealDto);

        //拿到集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) ->{
            item.setSetmealId(String.valueOf(setmealDto.getId()));
            return item;
        }).collect(Collectors.toList());
        //套餐id setmealId 是没有的

        //保存套餐和菜品的关联信息 操作setmeal_dish 执行insert操作
        setmealDishService.saveBatch(setmealDishes);

    }

    //删除套餐 和 菜品的关联数据
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //只有停售的才能删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if (count > 0){
            //如果不能删除 抛出业务异常
            throw new CustomException("套擦正在售卖中,不能删除");
        }
        //如果可以删除 先删除套餐表中的数据 setmeal
        this.removeByIds(ids);
        //在删除 关系表中的数据 setmeal_dish
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);

        setmealDishService.remove(queryWrapper1);

    }
}




